import React, { useState } from 'react';
import { Layout, Form, Input, Button, Space, Card, Select, Typography, Drawer, message, Dropdown, Modal } from 'antd';
import { PlusOutlined, MinusCircleOutlined, DownloadOutlined, LeftOutlined, RightOutlined, CopyOutlined } from '@ant-design/icons';
import type { FormListFieldData } from 'antd';

const { Header, Content } = Layout;
const { Title } = Typography;

const languages = [
  { value: 'en', label: 'English' },
  { value: 'zh', label: '中文' },
  { value: 'ja', label: '日本語' },
  { value: 'ko', label: '한국어' }
];

interface LanguageData {
  [key: string]: string;
}

interface MultiLanguageData {
  [language: string]: LanguageData;
}

const App: React.FC = () => {
  const [form] = Form.useForm();
  const [currentPage, setCurrentPage] = useState('');
  const [languageData, setLanguageData] = useState<MultiLanguageData>({});
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [keyCounters, setKeyCounters] = useState({
    page_ttl: 1,
    title: 1,
    word: 1,
    phrase: 1,
    para: 1
  });

  const handlePageChange = (value: string) => {
    setCurrentPage(value);
    const currentData = form.getFieldsValue();
    setLanguageData(prev => ({
      ...prev,
      [currentPage]: currentData
    }));
    form.setFieldsValue(languageData[value] || {});
  };

  const handleSubmit = (values: any) => {
    const translations = values.translations || [];
    const formattedData = translations.reduce((acc: LanguageData, item: any) => {
      acc[item.key] = item.value || 'xxx';
      return acc;
    }, {});

    const updatedData = {
      ...languageData,
      [currentPage]: formattedData
    };
    setLanguageData(updatedData);
    setDrawerVisible(true); // 保存成功后自动打开JSON预览抽屉
  };

  const downloadJSON = () => {
    const [mainMenu, page] = currentPage.split('/');
    const jsonString = JSON.stringify({
      [mainMenu]: {
        [page]: languageData[currentPage] || {}
      }
    }, null, 2);
    const blob = new Blob([jsonString], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'language.json';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const toggleDrawer = () => {
    setDrawerVisible(!drawerVisible);
  };

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header style={{ background: '#fff', padding: '0 16px' }}>
        <Title level={2}>多语言JSON生成器</Title>
      </Header>
      <Content style={{ padding: '24px', position: 'relative' }}>
        <Card>
          <Form form={form} onFinish={handleSubmit}>
            <Space style={{ marginBottom: 16 }} direction="horizontal">
              <Select
                placeholder="主菜单"
                style={{ width: 120 }}
                onChange={(value) => setCurrentPage(`${value}/${currentPage}`)}
                options={[
                  { value: 'component', label: 'component' },
                  { value: 'customer', label: 'customer' },
                  { value: 'enterprise', label: 'enterprise' },
                  { value: 'goods', label: 'goods' },
                  { value: 'manage', label: 'manage' },
                  { value: 'order', label: 'order' },
                  { value: 'propertyMaArea', label: 'propertyMaArea' },
                  { value: 'service', label: 'service' },
                  { value: 'venue', label: 'venue' }
                ]}
              />
              <Input
                value={currentPage.split('/')[1] || ''}
                onChange={(e) => {
                  const mainMenu = currentPage.split('/')[0];
                  handlePageChange(mainMenu ? `${mainMenu}/${e.target.value}` : e.target.value);
                }}
                placeholder="页面"
                style={{ width: 120 }}
              />
              <Button type="primary" htmlType="submit">
                保存当前页面
              </Button>
              <Button icon={<DownloadOutlined />} onClick={downloadJSON}>
                下载JSON
              </Button>
            </Space>
            <Form.List name="translations">
              {(fields: FormListFieldData[], { add, remove }) => {
                const addNewKey = (type: string) => {
                  const newKey = `${type}_${keyCounters[type]}`;
                  const fieldsArray = form.getFieldValue('translations') || [];
                  
                  // 定义分组顺序
                  const groupOrder = ['page_ttl', 'title', 'word', 'phrase', 'para'];
                  
                  // 找到当前类型在分组顺序中的位置
                  const currentTypeIndex = groupOrder.indexOf(type);
                  
                  // 找到插入位置
                  let insertIndex = 0;
                  for (let i = 0; i < fieldsArray.length; i++) {
                    const fieldType = fieldsArray[i].key.split('_')[0];
                    const fieldTypeIndex = groupOrder.indexOf(fieldType);
                    
                    if (fieldTypeIndex > currentTypeIndex) {
                      break;
                    }
                    if (fieldType === type || fieldTypeIndex < currentTypeIndex) {
                      insertIndex = i + 1;
                    }
                  }
                  
                  // 在指定位置插入新key
                  const updatedFields = [
                    ...fieldsArray.slice(0, insertIndex),
                    { key: newKey },
                    ...fieldsArray.slice(insertIndex)
                  ];
                  
                  form.setFieldValue('translations', updatedFields);
                  setKeyCounters(prev => ({
                    ...prev,
                    [type]: prev[type] + 1
                  }));
                };
                
                return (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                        <div style={{ padding: '5px 11px', background: '#f5f5f5', borderRadius: '6px' }}>
                          {form.getFieldValue(['translations', name, 'key'])}
                        </div>
                        <Form.Item
                          {...restField}
                          name={[name, 'value']}
                        >
                          <Input placeholder="翻译" />
                        </Form.Item>
                        <Button
                          type="text"
                          icon={<CopyOutlined />}
                          size="small"
                          onClick={async () => {
                            const key = form.getFieldValue(['translations', name, 'key']);
                            const value = form.getFieldValue(['translations', name, 'value']);
                            const [mainMenu, page] = currentPage.split('/');
                            if (!mainMenu || !page) {
                              message.error('请先选择主菜单和页面');
                              return;
                            }
                            const copyText = `t('${mainMenu}:${page}.${key}')`;  // 修改这里，使用key而不是value
                            try {
                              await navigator.clipboard.writeText(copyText);
                              message.success({
                                content: (
                                  <div>
                                    <div>复制成功</div>
                                    <div style={{ wordBreak: 'break-all' }}>{copyText}</div>
                                  </div>
                                ),
                                duration: 3
                              });
                            } catch (err) {
                              message.error({
                                content: '复制失败：请检查浏览器权限设置',
                                duration: 3
                              });
                              console.error('Copy failed:', err);
                            }
                          }}
                          style={{ padding: '4px 8px' }}
                        />
                        <MinusCircleOutlined onClick={() => remove(name)} />
                      </Space>
                    ))}
                    <Form.Item>
                      <Space direction="horizontal" wrap style={{ display: 'flex', justifyContent: 'flex-start' }}>
                        {Object.entries(keyCounters).map(([type, _]) => (
                          <Dropdown.Button
                            key={type}
                            type="dashed"
                            icon={<PlusOutlined />}
                            onClick={() => addNewKey(type)}
                            menu={{
                              items: [
                                {
                                  key: '5',
                                  label: '+5个',
                                  onClick: () => {
                                    const fieldsArray = form.getFieldValue('translations') || [];
                                    const groupOrder = ['page_ttl', 'title', 'word', 'phrase', 'para'];
                                    const currentTypeIndex = groupOrder.indexOf(type);
                                    let insertIndex = 0;
                                    for (let i = 0; i < fieldsArray.length; i++) {
                                      const fieldType = fieldsArray[i].key.split('_')[0];
                                      const fieldTypeIndex = groupOrder.indexOf(fieldType);
                                      if (fieldTypeIndex > currentTypeIndex) {
                                        break;
                                      }
                                      if (fieldType === type || fieldTypeIndex < currentTypeIndex) {
                                        insertIndex = i + 1;
                                      }
                                    }
                                    const newKeys = Array.from({length: 5}, (_, i) => ({
                                      key: `${type}_${keyCounters[type] + i}`
                                    }));
                                    const updatedFields = [
                                      ...fieldsArray.slice(0, insertIndex),
                                      ...newKeys,
                                      ...fieldsArray.slice(insertIndex)
                                    ];
                                    form.setFieldValue('translations', updatedFields);
                                    setKeyCounters(prev => ({
                                      ...prev,
                                      [type]: prev[type] + 5
                                    }));
                                  }
                                },
                                {
                                  key: '10',
                                  label: '+10个',
                                  onClick: () => {
                                    const fieldsArray = form.getFieldValue('translations') || [];
                                    const groupOrder = ['page_ttl', 'title', 'word', 'phrase', 'para'];
                                    const currentTypeIndex = groupOrder.indexOf(type);
                                    let insertIndex = 0;
                                    for (let i = 0; i < fieldsArray.length; i++) {
                                      const fieldType = fieldsArray[i].key.split('_')[0];
                                      const fieldTypeIndex = groupOrder.indexOf(fieldType);
                                      if (fieldTypeIndex > currentTypeIndex) {
                                        break;
                                      }
                                      if (fieldType === type || fieldTypeIndex < currentTypeIndex) {
                                        insertIndex = i + 1;
                                      }
                                    }
                                    const newKeys = Array.from({length: 10}, (_, i) => ({
                                      key: `${type}_${keyCounters[type] + i}`
                                    }));
                                    const updatedFields = [
                                      ...fieldsArray.slice(0, insertIndex),
                                      ...newKeys,
                                      ...fieldsArray.slice(insertIndex)
                                    ];
                                    form.setFieldValue('translations', updatedFields);
                                    setKeyCounters(prev => ({
                                      ...prev,
                                      [type]: prev[type] + 10
                                    }));
                                  }
                                },
                                {
                                  key: '20',
                                  label: '+20个',
                                  onClick: () => {
                                    const fieldsArray = form.getFieldValue('translations') || [];
                                    const groupOrder = ['page_ttl', 'title', 'word', 'phrase', 'para'];
                                    const currentTypeIndex = groupOrder.indexOf(type);
                                    let insertIndex = 0;
                                    for (let i = 0; i < fieldsArray.length; i++) {
                                      const fieldType = fieldsArray[i].key.split('_')[0];
                                      const fieldTypeIndex = groupOrder.indexOf(fieldType);
                                      if (fieldTypeIndex > currentTypeIndex) {
                                        break;
                                      }
                                      if (fieldType === type || fieldTypeIndex < currentTypeIndex) {
                                        insertIndex = i + 1;
                                      }
                                    }
                                    const newKeys = Array.from({length: 20}, (_, i) => ({
                                      key: `${type}_${keyCounters[type] + i}`
                                    }));
                                    const updatedFields = [
                                      ...fieldsArray.slice(0, insertIndex),
                                      ...newKeys,
                                      ...fieldsArray.slice(insertIndex)
                                    ];
                                    form.setFieldValue('translations', updatedFields);
                                    setKeyCounters(prev => ({
                                      ...prev,
                                      [type]: prev[type] + 20
                                    }));
                                  }
                                },
                                {
                                  key: '30',
                                  label: '+30个',
                                  onClick: () => {
                                    const fieldsArray = form.getFieldValue('translations') || [];
                                    const groupOrder = ['page_ttl', 'title', 'word', 'phrase', 'para'];
                                    const currentTypeIndex = groupOrder.indexOf(type);
                                    let insertIndex = 0;
                                    for (let i = 0; i < fieldsArray.length; i++) {
                                      const fieldType = fieldsArray[i].key.split('_')[0];
                                      const fieldTypeIndex = groupOrder.indexOf(fieldType);
                                      if (fieldTypeIndex > currentTypeIndex) {
                                        break;
                                      }
                                      if (fieldType === type || fieldTypeIndex < currentTypeIndex) {
                                        insertIndex = i + 1;
                                      }
                                    }
                                    const newKeys = Array.from({length: 30}, (_, i) => ({
                                      key: `${type}_${keyCounters[type] + i}`
                                    }));
                                    const updatedFields = [
                                      ...fieldsArray.slice(0, insertIndex),
                                      ...newKeys,
                                      ...fieldsArray.slice(insertIndex)
                                    ];
                                    form.setFieldValue('translations', updatedFields);
                                    setKeyCounters(prev => ({
                                      ...prev,
                                      [type]: prev[type] + 30
                                    }));
                                  }
                                },
                                {
                                  key: 'batch',
                                  label: '批量文本',
                                  onClick: () => {
                                    Modal.confirm({
                                      title: '批量添加文本',
                                      content: (
                                        <Input.TextArea
                                          rows={10}
                                          placeholder="请输入文本，每行一个条目"
                                          id="batchTextArea"
                                        />
                                      ),
                                      onOk: () => {
                                        const textArea = document.getElementById('batchTextArea') as HTMLTextAreaElement;
                                        if (!textArea) return;
                                        
                                        const lines = textArea.value.split('\n').filter(line => line.trim());
                                        if (lines.length === 0) return;
                                        
                                        const fieldsArray = form.getFieldValue('translations') || [];
                                        const groupOrder = ['page_ttl', 'title', 'word', 'phrase', 'para'];
                                        const currentTypeIndex = groupOrder.indexOf(type);
                                        
                                        let insertIndex = 0;
                                        for (let i = 0; i < fieldsArray.length; i++) {
                                          const fieldType = fieldsArray[i].key.split('_')[0];
                                          const fieldTypeIndex = groupOrder.indexOf(fieldType);
                                          if (fieldTypeIndex > currentTypeIndex) {
                                            break;
                                          }
                                          if (fieldType === type || fieldTypeIndex < currentTypeIndex) {
                                            insertIndex = i + 1;
                                          }
                                        }
                                        
                                        const newFields = lines.map((line, i) => ({
                                          key: `${type}_${keyCounters[type] + i}`,
                                          value: line.trim()
                                        }));
                                        
                                        const updatedFields = [
                                          ...fieldsArray.slice(0, insertIndex),
                                          ...newFields,
                                          ...fieldsArray.slice(insertIndex)
                                        ];
                                        
                                        form.setFieldValue('translations', updatedFields);
                                        setKeyCounters(prev => ({
                                          ...prev,
                                          [type]: prev[type] + lines.length
                                        }));
                                      }
                                    });
                                  }
                                }
                              ]
                            }}
                          >
                            添加{type}
                          </Dropdown.Button>
                        ))}
                      </Space>
                    </Form.Item>
                  </>
                );
              }}
            </Form.List>
          </Form>
        </Card>

        <div
          style={{
            position: 'fixed',
            right: drawerVisible ? '400px' : 0,
            top: '50%',
            transform: 'translateY(-50%)',
            zIndex: 1000,
            cursor: 'pointer',
            background: '#1890ff',
            padding: '12px 4px',
            borderRadius: '4px 0 0 4px',
            color: '#fff',
            transition: 'right 0.3s'
          }}
          onClick={toggleDrawer}
        >
          {drawerVisible ? <RightOutlined /> : <LeftOutlined />}
        </div>

        <Drawer
          title="JSON预览"
          placement="right"
          onClose={toggleDrawer}
          open={drawerVisible}
          width={400}
          mask={true}
          maskClosable={true}
          style={{ position: 'fixed' }}
        >
          <pre style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>
            {JSON.stringify({
              [currentPage.split('/')[0]]: {
                [currentPage.split('/')[1]]: languageData[currentPage] || {}
              }
            }, null, 2)}
          </pre>
        </Drawer>
      </Content>
    </Layout>
  );
};

export default App;